import UploadFile from "@/components/FileUpload";
import request from "@/utils/request";
import { ColProps, Form, Input, message, Modal, Select } from "antd";
import React, { useCallback, useMemo } from "react";

function createBanner(banner: any) {
  return request('/api/pic/carousel', {
    method: 'POST',
    data: { ...banner, enabled: 0 }
  })
}

export function useAddBanner(props: BannerAddModalProps) {
  const [form] = Form.useForm()


  const layout = useMemo<{
    labelCol: ColProps
    wrapperCol: ColProps
  }>(() => {
    return {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    }
  }, [])


  const handleSubmit = useCallback(() => {


    const submit = async () => {
      const result = await form.validateFields()
      if (result) {
        try {

          const data = form.getFieldsValue()
          const { data: { id } } = await createBanner(data)
          if (id) {
            props.onOk({
              ...data,
              id
            })
          }
        } catch (e) {

        }
      }
    }

    submit()

  }, [form, props])
  return {
    form,
    layout,
    handleSubmit
  }
}

type BannerAddModalProps = {
  open: boolean
  onClose: () => void
  onOk: (bannerId: number) => void
}

export function BannerAddModal(props: BannerAddModalProps) {

  const { form, layout, handleSubmit } = useAddBanner(props)
  return (
    <Modal
      destroyOnClose
      visible={props.open}
      onCancel={props.onClose}
      title={'新增Banner'}
      onOk={() => {
        handleSubmit()
      }}

    >
      <Form form={form} {...layout} >
        <Form.Item
          label="标题"
          required
          name="name"
          rules={[
            { required: true, message: '标题必填' }
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="上传图片"
          required
          name="image_url"
          rules={[
            { required: true, message: '图片必传' }
          ]}
        >
          <UploadFile />
        </Form.Item>
        <Form.Item
          label="选择链接"

          name="link"
        >
          <Select style={{ width: '100%' }}>
            <Select.Option>商品分类</Select.Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  )
}